<?php
namespace app\index\controller;
use \think\Controller;
use \think\Db;
use \think\Request;
use \think\facade\Config;//引入配置
use PHPMailer\PHPMailer\PHPMailer;//引入邮件类
use TCPDF;
use think\captcha\Captcha;
use \think\facade\Session;
use OSS\OssClient;
use OSS\Core\OssException;

class Oos extends Controller
{


    public function conn(){
        $ossClient = new OssClient(Config::get('app.accessKeyId'), Config::get('app.accessKeySecret'), Config::get('app.endpoint'), false);
        return $ossClient;
    }



    /*转移图片*/
    public function transfer_files(){
        ini_set('max_execution_time', 0);
        $to='pdf/ball-bearing/flanged-ball-bearings/';

        $ossClient = $this->conn();

        $sql="SELECT * FROM product_middle_table WHERE dimg LIKE '%static%'";
        $data=Db::query($sql);

        foreach ($data as $key => $value) {
            $name=urldecode(ltrim($value['dimg'],'/'));


            $exist = $ossClient->doesObjectExist(Config::get('app.bucket'), $name);
            if($exist==1){
                $d=explode('/',$name);
                $end=end($d);
                $suffix=substr($end,-3);
                $toObject=$to.str_replace('-','',show_update_fuhao_url($value['Product_Number'])).'.'.$suffix;

                $ossClient->copyObject(Config::get('app.bucket'),$name,Config::get('app.bucket'), $toObject);
                echo "update product_middle_table set dimg='/".$toObject."' where Product_Number='".$value['Product_Number']."';</br>";
            }else{
                echo "update product_middle_table set dimg=null where Product_Number='".$value['Product_Number']."';</br>";
            }
        }
    }

    public function check_pdf(){
        ini_set('max_execution_time', 0);

        $ossClient = $this->conn();
        $sql="SELECT url_product,pdf,id FROM lily_products where pdf IS NOT null and pdf!=''";
        $data1=Db::query($sql);


        foreach ($data1 as $key => $value) {
            $name=ltrim($value['pdf'],'/');

            $exist = $ossClient->doesObjectExist(Config::get('app.bucket'), $name);
            if($exist!=1){
                echo "inset into a (pid,url_product) values (".$value['id'].",'".$value['url_product']."');</br>";
            }
        }
    }
    /*删除jpg文件*/
    public function transfer_files1(){
        ini_set('max_execution_time', 0);
        $to='pdf/ball-bearing/flanged-ball-bearings/';

        $ossClient = $this->conn();

        $options = array(
            // 设置每页列举200个文件。
            OssClient::OSS_MAX_KEYS=>200,
            OssClient::OSS_PREFIX =>$to
        );
        do{
            $result = $ossClient->listObjects(Config::get('app.bucket'),$options);
            $objectList = $result->getObjectList();

            foreach ($objectList as $objectInfo) {
                $url=$objectInfo->getKey();
                $suffix=pathinfo($url, PATHINFO_EXTENSION );
                $i=1;
                if($suffix=='jpg'){
                    try{
                        $ossClient->deleteObject(Config::get('app.bucket'), $url);
                        $i++;
                        echo $i."</br>";
                    } catch(OssException $e) {
                        printf($e->getMessage() . "\n");
                        return;
                    }


                }
            }
            $options[OssClient::OSS_MARKER] = $result->getNextMarker();
        }while($result->getIsTruncated() === 'true');
    }


    /*pdf转移*/
    public function transfer_files_pdf(){
        ini_set('max_execution_time', 0);
        $to='pdf/cam-followers/cam-follower-smith/';

        $ossClient = $this->conn();

        $sql="SELECT  Product_Number FROM cam_followers_smith";
        $data=Db::query($sql);

        foreach ($data as $key => $value) {
            $name="static/upload/product/pdf/cam-follower-smith/".str_replace('-', '',str_replace('/', '',str_replace(' ', '', strtolower($value['Product_Number'])))).".pdf";


            $exist = $ossClient->doesObjectExist(Config::get('app.bucket'), $name);
            if($exist==1){
                $d=explode('/',$name);
                $end=end($d);
                $suffix=substr($end,-3);
                $toObject=$to.str_replace('-','',show_update_fuhao_url($value['Product_Number'])).'.'.$suffix;

                $ossClient->copyObject(Config::get('app.bucket'),$name,Config::get('app.bucket'), $toObject);
                echo "update product_middle_table set pdf='/".$toObject."' where Product_Number='".$value['Product_Number']."';</br>";
            }else{
                echo "update product_middle_table set pdf=null where Product_Number='".$value['Product_Number']."';</br>";
            }
        }
    }


    /*3d转移*/
    public function transfer_files_stp(){
        ini_set('max_execution_time', 0);
        $to='stp/spherical-plain-bearings-rod-ends/';

        $ossClient = $this->conn();

        $sql="SELECT  Product_Number FROM spherical_plain_rod_ends where class_id=656";
        $data=Db::query($sql);


        foreach ($data as $key => $value) {

            $name214="static/stp/spherical-plain-bearings/rod-ends/female-thread/LILY_".str_replace('/','_',$value['Product_Number'])."_(AP214).stp";
            $name203="static/stp/spherical-plain-bearings/rod-ends/female-thread/LILY_".str_replace('/','_',$value['Product_Number'])."_(AP203).stp";


            $new214=$this->transfer($name214,$value['Product_Number'],$to,'214');

            $new203=$this->transfer($name203,$value['Product_Number'],$to,'203');

            if(!empty($new214)&&!empty($new203)){
                $data=array('stp214'=>"/".$new214,'stp203'=>"/".$new203);
            }
            if(!empty($new214)&&empty($new203)){
                $data=array('stp214'=>"/".$new214);
            }
            if(empty($new214)&&!empty($new203)){
                $data=array('stp203'=>"/".$new203);
            }

            if(empty($new214)&&empty($new203)){
                $data=null;
            }

            /*if(!empty($new203)){
               $data=array('stp203'=>"/".$new203);
            }else{
               $data=null;
            }*/
            if(!empty($data)){
                echo "update product_middle_table set stp='".json_encode($data)."' where Product_Number='".$value['Product_Number']."';</br>";
            }

        }
    }

    public function transfer($name,$Product_Number,$to,$type){
        $ossClient = $this->conn();
        $exist = $ossClient->doesObjectExist(Config::get('app.bucket'), $name);
        if($exist==1){
            $d=explode('/',$name);
            $end=end($d);
            $suffix=pathinfo($end, PATHINFO_EXTENSION );

            $toObject=$to.$type.'/'.str_replace('-','',show_update_fuhao_url($Product_Number)).'.'.$suffix;

            $ossClient->copyObject(Config::get('app.bucket'),$name,Config::get('app.bucket'), $toObject);
            return $toObject;
        }else{
            return null;
        }
    }



    /*banner 上传*/
    public function upload_banner(Request $request){
        $ossClient = $this->conn();
        $post=$request->post();

        $tempurl="static/temp/".$_FILES["file"]["name"]; /*服务器暂时存放目录 上传oss后删除*/

        $allowedExts = Config::get('app.allowedExts');//允许上传的图片后缀
        $size = Config::get('app.upload_file_size');//允许上传的图片大小
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);// 获取文件后缀名

        // 目标路径。
        $object = "banner/".file_name().".".$extension;
        // 本地文件的完整路径。
        $filePath = $tempurl;

        if (($_FILES["file"]["size"] < $size) && in_array($extension, $allowedExts)){

            if ($_FILES["file"]["error"] > 0){
                $result=['status'=>'0','msg'=>"'".$_FILES["file"]["error"]."'"];
                return json($result);
            }else{
                /*移动到上传目录*/
                move_uploaded_file($_FILES["file"]["tmp_name"],$tempurl);

                /*移动到oss*/
                try{
                    $ossClient = new OssClient(Config::get('app.accessKeyId'), Config::get('app.accessKeySecret'), Config::get('app.endpoint'));

                    $ossClient->uploadFile(Config::get('app.bucket'), $object, $filePath);

                    if($extension=='mp4'){ $type=2;}else{ $type=1;}

                    unlink($filePath);/*删除占用服务器文件*/

                    $result=['status'=>'1','msg'=>'上传成功','newname'=>Config::get('app.images_host').'/'.$object,'type'=>$type];

                    return json($result);

                } catch(OssException $e) {
                    $result=['status'=>0,'msg'=>$e->getMessage()];
                    return json($result);
                }
            }
        }else{
            $result=['status'=>'0','msg'=>'非法的文件格式'];
            return json($result);
        }
    }


    /*博客 上传*/
    public function upload_blog(Request $request){
        $ossClient = $this->conn();
        $post=$request->post();

        $tempurl="static/temp/".$_FILES["imgFile"]["name"]; /*服务器暂时存放目录 上传oss后删除*/

        $allowedExts = Config::get('app.allowedExts');//允许上传的图片后缀
        $size = Config::get('app.upload_file_size');//允许上传的图片大小
        $temp = explode(".", $_FILES["imgFile"]["name"]);
        $extension = end($temp);// 获取文件后缀名

        // 目标路径。
        $object = "blog/".file_name().".".$extension;
        // 本地文件的完整路径。
        $filePath = $tempurl;

        if (($_FILES["imgFile"]["size"] < $size) && in_array($extension, $allowedExts)){

            if ($_FILES["imgFile"]["error"] > 0){
                $result=['error'=>1,'message'=>"'".$_FILES["imgFile"]["error"]."'"];
                return json($result);
            }else{
                /*移动到上传目录*/
                move_uploaded_file($_FILES["imgFile"]["tmp_name"],$tempurl);

                /*移动到oss*/
                try{
                    $ossClient = new OssClient(Config::get('app.accessKeyId'), Config::get('app.accessKeySecret'), Config::get('app.endpoint'));

                    $ossClient->uploadFile(Config::get('app.bucket'), $object, $filePath);

                    unlink($filePath);/*删除占用服务器文件*/

                    $result=['error'=>0,'url'=>Config::get('app.images_host').'/'.$object];

                    return json($result);

                } catch(OssException $e) {
                    $result=['error'=>1,'message'=>$e->getMessage()];
                    return json($result);
                }
            }
        }else{
            $result=['error'=>1,'message'=>'非法的文件格式'];
            return json($result);
        }
    }

    /*博客 上传 主图*/
    public function upload_blog_img(Request $request){
        $ossClient = $this->conn();
        $post=$request->post();

        $tempurl="static/temp/".$_FILES["file"]["name"]; /*服务器暂时存放目录 上传oss后删除*/

        $allowedExts = Config::get('app.allowedExts');//允许上传的图片后缀
        $size = Config::get('app.upload_file_size');//允许上传的图片大小
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);// 获取文件后缀名

        // 目标路径。
        $object = "blog/".file_name().".".$extension;
        // 本地文件的完整路径。
        $filePath = $tempurl;

        if (($_FILES["file"]["size"] < $size) && in_array($extension, $allowedExts)){

            if ($_FILES["file"]["error"] > 0){
                $result=['status'=>'0','msg'=>"'".$_FILES["file"]["error"]."'"];
                return json($result);
            }else{
                /*移动到上传目录*/
                move_uploaded_file($_FILES["file"]["tmp_name"],$tempurl);

                /*移动到oss*/
                try{
                    $ossClient = new OssClient(Config::get('app.accessKeyId'), Config::get('app.accessKeySecret'), Config::get('app.endpoint'));

                    $ossClient->uploadFile(Config::get('app.bucket'), $object, $filePath);

                    if($extension=='mp4'){ $type=2;}else{ $type=1;}

                    unlink($filePath);/*删除占用服务器文件*/

                    $result=['status'=>'1','msg'=>'上传成功','newname'=>Config::get('app.images_host').'/'.$object,'type'=>$type];

                    return json($result);

                } catch(OssException $e) {
                    $result=['status'=>0,'msg'=>$e->getMessage()];
                    return json($result);
                }
            }
        }else{
            $result=['status'=>'0','msg'=>'非法的文件格式'];
            return json($result);
        }
    }
    /*分类的tdk等上传*/
    public function upload_classdes(Request $request){
        $ossClient = $this->conn();
        $post=$request->post();

        $tempurl="static/temp/".$_FILES["file"]["name"]; /*服务器暂时存放目录 上传oss后删除*/

        $allowedExts = Config::get('app.allowedExts');//允许上传的图片后缀
        $size = Config::get('app.upload_file_size');//允许上传的图片大小
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);// 获取文件后缀名

        // 目标路径。
        $object = "classdes/".file_name().".".$extension;
        // 本地文件的完整路径。
        $filePath = $tempurl;

        if (($_FILES["file"]["size"] < $size) && in_array($extension, $allowedExts)){

            if ($_FILES["file"]["error"] > 0){
                $result=['error'=>1,'message'=>"'".$_FILES["file"]["error"]."'"];
                return json($result);
            }else{
                /*移动到上传目录*/
                move_uploaded_file($_FILES["file"]["tmp_name"],$tempurl);

                /*移动到oss*/
                try{
                    $ossClient = new OssClient(Config::get('app.accessKeyId'), Config::get('app.accessKeySecret'), Config::get('app.endpoint'));

                    $ossClient->uploadFile(Config::get('app.bucket'), $object, $filePath);

                    unlink($filePath);/*删除占用服务器文件*/

                    //$result=['error'=>0,'url'=>Config::get('app.images_host').'/'.$object];
                    $result=['status'=>'1','msg'=>'上传成功','url'=>Config::get('app.images_host').'/'.$object];

                    return json($result);

                } catch(OssException $e) {
                    //$result=['error'=>1,'message'=>$e->getMessage()];
                    $result=['status'=>0,'msg'=>$e->getMessage()];
                    return json($result);
                }
            }
        }else{
            $result=['error'=>1,'message'=>'非法的文件格式'];
            return json($result);
        }
    }

    public function tinymce_upload(Request $request){

        $ossClient = $this->conn();
        $post=$request->post();

        $tempurl="static/temp/".$_FILES["file"]["name"]; /*服务器暂时存放目录 上传oss后删除*/

        $allowedExts = Config::get('app.allowedExts');//允许上传的图片后缀
        $size = Config::get('app.upload_file_size');//允许上传的图片大小
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);// 获取文件后缀名

// 目标路径。
        $object = "classdes/".file_name().".".$extension;
// 本地文件的完整路径。
        $filePath = $tempurl;

        if (($_FILES["file"]["size"] < $size) && in_array($extension, $allowedExts)){

            if ($_FILES["file"]["error"] > 0){
                $result=['error'=>1,'message'=>"'".$_FILES["file"]["error"]."'"];
                return json($result);
            }else{
                /*移动到上传目录*/
                move_uploaded_file($_FILES["file"]["tmp_name"],$tempurl);

                /*移动到oss*/
                try{
                    $ossClient = new OssClient(Config::get('app.accessKeyId'), Config::get('app.accessKeySecret'), Config::get('app.endpoint'));

                    $ossClient->uploadFile(Config::get('app.bucket'), $object, $filePath);

                    unlink($filePath);/*删除占用服务器文件*/

//$result=['error'=>0,'url'=>Config::get('app.images_host').'/'.$object];
//$result=['status'=>'1','msg'=>'上传成功','url'=>Config::get('app.images_host').'/'.$object];

//return json($result);
                    echo json_encode(array('location' => Config::get('app.images_host').'/'.$object));

                } catch(OssException $e) {
//$result=['error'=>1,'message'=>$e->getMessage()];
//$result=['status'=>0,'msg'=>$e->getMessage()];
//return json($result);
                    echo json_encode(array('location' => ''));
                }
            }
        }else{
//$result=['error'=>1,'message'=>'非法的文件格式'];
//return json($result);
            echo json_encode(array('location' => ''));
        }
    }

    /*pdf 生成 站点地图*/
    public function pdf_site_map(){
        set_time_limit(0);
        $filename='site_pdf_map';

        $strxml="<?xml version='1.0' encoding='UTF-8'?>\n<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9' xmlns:xhtml='http://www.w3.org/1999/xhtml' xmlns:image='http://www.google.com/schemas/sitemap-image/1.1'>\n";
        $strtxt="";
        $ossClient = $this->conn();
        $prefix = 'pdf/';
        $prefix_arr=[];
        $options = array(
            'delimiter' => '',
            'prefix' => $prefix,
            OssClient::OSS_MAX_KEYS=>1000,
        );
        $num=30000;
        $m=0;
        $n=1;

        do{
            $listObjectInfo = $ossClient->listObjects(Config::get('app.bucket'),$options);

            $objectList = $listObjectInfo->getObjectList();

            if (!empty($objectList)) {
                foreach ($objectList as $objectInfo) {
                    $ossurl=$objectInfo->getKey();
                    if(count(explode('.',$ossurl))>1){
                        if($m%$num==0 && $m!=0){
                            $strxml.="\n<url>\n";
                            $strxml.="<loc><![CDATA[".Config::get('app.images_host').'/'.$ossurl."]]></loc>\n";
                            $strxml.="<xhtml:link rel='alternate' hreflang='en' href='".Config::get('app.images_host').'/'.$ossurl."'/>\n";
                            $strxml.="<xhtml:link rel='alternate' hreflang='zh' href='https://image.lilybearing.com/".$ossurl."'/>\n";
                            $strxml.="<lastmod>".date('Y-m-d',time())."</lastmod>\n</url>";
                            $strxml.="\n</urlset>";
                            $load=explode('application', __DIR__);
                            if(file_exists($load[0].'public/'.$filename.$n.".xml")){
                                unlink($load[0].'public/'.$filename);
                            }
                            $myfiletxt=fopen($load[0].'public/'.$filename.$n.".xml", "a+");
                            fwrite($myfiletxt, $strxml);
                            fclose($myfiletxt);
                            $n++;
                            $strxml="<?xml version='1.0' encoding='UTF-8'?>\n<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9' xmlns:xhtml='http://www.w3.org/1999/xhtml' xmlns:image='http://www.google.com/schemas/sitemap-image/1.1'>\n";
                        }else{
                            $strxml.="\n<url>\n";
                            $strxml.="<loc><![CDATA[".Config::get('app.images_host').'/'.$ossurl."]]></loc>\n";
                            $strxml.="<xhtml:link rel='alternate' hreflang='en' href='".Config::get('app.images_host').'/'.$ossurl."'/>\n";
                            $strxml.="<xhtml:link rel='alternate' hreflang='zh' href='https://image.lilybearing.com/".$ossurl."'/>\n";
                            $strxml.="<lastmod>".date('Y-m-d',time())."</lastmod>\n</url>";
                        }
                        $m++;
                        $strtxt.=Config::get('app.images_host').'/'.$ossurl."\n";
                    }
                }

            }
            $options[OssClient::OSS_MARKER] = $listObjectInfo->getNextMarker();
        }while($listObjectInfo->getIsTruncated() === 'true');

        $strxml.="\n</urlset>";

        $load=explode('application', __DIR__);
        if(file_exists($load[0].'public/'.$filename.'.xml')){
            unlink($load[0].'public/'.$filename);
        }
        $myfiletxt=fopen($load[0].'public/'.$filename.'.xml', "a+");
        fwrite($myfiletxt, $strxml);
        fclose($myfiletxt);

        $myfiletxt=fopen($load[0].'public/sitemap.txt', "a+");
        fwrite($myfiletxt, $strtxt);
        fclose($myfiletxt);
    }





}